package com.hello.service;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.springframework.oxm.Marshaller;
import org.springframework.oxm.Unmarshaller;

//import com.hello.domain.TestPerson;

public class MarshallingServiceImpl implements MarshallingService {
	
	private static String FILE_PREFIX = "../config/";
	private static final String FILE_SUFFIX = ".xml";

	//private TestPerson configurations;
	private Marshaller marshaller;
	private Unmarshaller unmarshaller;
	
	@Override
	public Object loadConfiguration(String name) throws IOException {
		// TODO Auto-generated method stub
		FileInputStream is = null;
		try {
			is = new FileInputStream(FILE_PREFIX + name + FILE_SUFFIX);
			Object object = this.unmarshaller.unmarshal(new StreamSource(is));
			return object;
		} finally {
			if(is != null) {
				is.close();
			}
		}
	}

	@Override
	public void saveConfiguration(String name, Object object) throws IOException {
		// TODO Auto-generated method stub
		FileOutputStream os = null;
		try {
			os = new FileOutputStream(FILE_PREFIX + name + FILE_SUFFIX);
			this.marshaller.marshal(object, new StreamResult(os));
		} finally {
			if(os != null) {
				os.close();
			}
		}
	}

	public void setMarshaller(Marshaller marshaller) {
		this.marshaller = marshaller;
	}


	public void setUnmarshaller(Unmarshaller unmarshaller) {
		this.unmarshaller = unmarshaller;
	}


}
